﻿using System;
using System.Collections.Generic;

namespace Leo.Awesome.Infrastructure
{
    public static class TreeExtensions
    {
        public static List<T> ToList<T>(this IEnumerable<T> roots, Func<T, IEnumerable<T>> getChildItems)
        {
            List<T> list = new List<T>();
            foreach (var root in roots)
            {
                TraverseTree(root, getChildItems, list);
            }
            return list;
        }

        private static void TraverseTree<T>(T node, Func<T, IEnumerable<T>> getChildItems, List<T> list)
        {
            list.Add(node);
            var childItems = getChildItems(node);
            if (childItems != null)
            {
                foreach (var child in childItems)
                {
                    TraverseTree(child, getChildItems, list);
                }
            }
        }
    }
}
